package handler

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"goserver/internal/service"
	"goserver/internal/model"
	"goserver/internal/middleware"
	"goserver/internal/config"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
)

type Router struct {
	deviceService   *service.DeviceService
	messageModel    *model.MessageModel
	wsHandler       *WebSocketHandler
	authHandler     *AuthHandler
	authMiddleware  *middleware.AuthMiddleware
	robotCodeHandler *RobotCodeHandler
	userHandler     *UserHandler
	statsHandler    *StatsHandler
}

func NewRouter(
	deviceService *service.DeviceService,
	messageModel *model.MessageModel,
	authHandler *AuthHandler,
	authMiddleware *middleware.AuthMiddleware,
	robotCodeHandler *RobotCodeHandler,
	userHandler *UserHandler,
	statsHandler *StatsHandler,
) *Router {
	return &Router{
		deviceService:    deviceService,
		messageModel:     messageModel,
		wsHandler:        NewWebSocketHandler(deviceService, messageModel),
		authHandler:      authHandler,
		authMiddleware:   authMiddleware,
		robotCodeHandler: robotCodeHandler,
		userHandler:      userHandler,
		statsHandler:     statsHandler,
	}
}

func (r *Router) SetupRoutes(engine *gin.Engine) {
	// 静态文件
	engine.Static("/static", "./static")
	
	// WebSocket连接
	engine.GET("/robot/connect", func(c *gin.Context) {
		r.wsHandler.HandleWebSocket(c.Writer, c.Request)
	})

	// API路由组
	api := engine.Group("/api")
	{
		// 公开路由
		api.GET("/health", r.GetHealth)  // 健康检查

		// 用户认证路由
		auth := api.Group("/auth")
		{
			auth.POST("/login", r.authHandler.Login)
			auth.POST("/register", r.authHandler.Register)
			auth.POST("/logout", r.authMiddleware.Auth(), r.authHandler.Logout)
		}

		// 需要认证的路由组
		authorized := api.Group("")
		authorized.Use(r.authMiddleware.Auth())
		{
			// 用户管理
			user := authorized.Group("/user")
			{
				user.GET("/info", r.userHandler.GetUserInfo)
				user.PUT("/info", r.userHandler.UpdateUserInfo)
				user.PUT("/password", r.userHandler.UpdatePassword)
			}

			// 消息管理
			message := authorized.Group("/message")
			{
				message.POST("/send", r.SendMessage)
				message.GET("/list", r.GetMessages)
			}

			// 机器人管理
			robot := authorized.Group("/robot")
			{
				robot.GET("/config", r.GetRobotConfig)
				robot.POST("/config", r.UpdateRobotConfig)
				robot.GET("/status", r.GetRobotStatus)
			}

			// 机器码管理
			robotCode := authorized.Group("/robot-code")
			{
				robotCode.POST("", r.robotCodeHandler.CreateRobotCodes)
				robotCode.GET("", r.robotCodeHandler.GetRobotCodes)
				robotCode.PUT("", r.robotCodeHandler.UpdateRobotCode)
				robotCode.DELETE("/:id", r.robotCodeHandler.DeleteRobotCode)
			}

			// 统计相关
			stats := authorized.Group("/stats")
			{
				stats.GET("/messages", r.statsHandler.GetMessageStats)
				stats.GET("/devices", r.statsHandler.GetDeviceStats)
				stats.GET("/robot-codes", r.statsHandler.GetRobotCodeStats)
			}
		}
	}

	// Swagger文档
	if config.GlobalConfig.Server.EnableSwagger {
		engine.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
	}
}

// @Summary 健康检查
// @Description 系统健康状态检查
// @Tags 系统
// @Produce json
// @Success 200 {object} Response{data=HealthResponse} "健康状态"
// @Router /health [get]
func (r *Router) GetHealth(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "ok",
		"data": map[string]interface{}{
			"status": "healthy",
			"time":   time.Now().Format(time.RFC3339),
		},
	})
}

// @Summary 发送消息
// @Description 发送消息到指定机器人
// @Tags 消息
// @Accept json
// @Produce json
// @Param data body SendMessageRequest true "消息内容"
// @Success 200 {object} Response{data=SendMessageResponse} "发送成功"
// @Failure 400 {object} Response "参数错误"
// @Failure 401 {object} Response "未授权"
// @Security Bearer
// @Router /message/send [post]
func (r *Router) SendMessage(c *gin.Context) {
	var req struct {
		RobotID string       `json:"robot_id" binding:"required"`
		Message model.Message `json:"message" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 验证机器码
	_, err := r.deviceService.ValidateRobotID(c.Request.Context(), req.RobotID)
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
		return
	}

	// 发送消息
	req.Message.RobotID = req.RobotID
	if err := r.wsHandler.SendMessage(req.RobotID, &req.Message); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"message": "指令已加入代发队列中！",
		"data": "1866043870117011456", // 模拟息ID
	})
}

// @Summary 获取消息列表
// @Description 获取指定机器人的消息列表
// @Tags 消息
// @Produce json
// @Param robot_id query string true "机器人ID"
// @Success 200 {object} Response{data=[]model.Message} "消息列表"
// @Failure 400 {object} Response "参数错误"
// @Failure 401 {object} Response "未授权"
// @Security Bearer
// @Router /message/list [get]
func (r *Router) GetMessages(c *gin.Context) {
	robotID := c.Query("robot_id")
	if robotID == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "missing robot_id"})
		return
	}

	messages, err := r.messageModel.QueryMessages(
		c.Request.Context(),
		robotID,
		time.Now().AddDate(0, 0, -7), // 最近7天
		time.Now(),
	)

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"data": messages,
	})
}

// 获取机器人配置
func (r *Router) GetRobotConfig(c *gin.Context) {
	robotID := c.Query("robot_id")
	if robotID == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "missing robot_id"})
		return
	}

	config, err := r.deviceService.GetRobotConfig(c.Request.Context(), robotID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"data": config,
	})
}

// 更新机器人配置
func (r *Router) UpdateRobotConfig(c *gin.Context) {
	var config service.RobotConfig
	if err := c.ShouldBindJSON(&config); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if err := r.deviceService.UpdateRobotConfig(c.Request.Context(), &config); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"message": "配置更新成功",
	})
}

// 获取机器人状态
func (r *Router) GetRobotStatus(c *gin.Context) {
	robotID := c.Query("robot_id")
	if robotID == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "missing robot_id"})
		return
	}

	config, err := r.deviceService.ValidateRobotID(c.Request.Context(), robotID)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"data": map[string]interface{}{
				"online": false,
				"error":  err.Error(),
			},
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"data": map[string]interface{}{
			"online":     true,
			"config":     config,
			"last_seen": time.Now(),
		},
	})
} 